<template>
  <view class="publish-demand-container">
    <!-- 顶部提示 -->
    <view class="tips-banner">
      <u-icon name="info-circle-fill" size="32" color="#5daf34"></u-icon>
      <text class="tips-text">填写详细需求，快速匹配优质教员</text>
    </view>

    <view class="form-content">
      <!-- 基本信息 -->
      <view class="form-section card">
        <view class="section-header">
          <view class="header-icon">
            <u-icon name="file-text-fill" size="36" color="#5daf34"></u-icon>
          </view>
          <text class="section-title">基本信息</text>
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">需求标题</text>
            <text class="required-star">*</text>
          </view>
          <input 
            class="item-input"
            v-model="form.title"
            placeholder="如：需要高中数学老师"
            maxlength="200"
            placeholder-class="input-placeholder"
          />
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">科目</text>
            <text class="required-star">*</text>
          </view>
          <view class="picker-wrapper" @click="showSubjectPicker = true">
            <text :class="{ 'placeholder': !form.subject }">
              {{ form.subject || '请选择科目' }}
            </text>
            <u-icon name="arrow-down" size="20" color="#999"></u-icon>
          </view>
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">年级</text>
          </view>
          <view class="picker-wrapper" @click="showGradePicker = true">
            <text :class="{ 'placeholder': !form.grade }">
              {{ form.grade || '请选择年级' }}
            </text>
            <u-icon name="arrow-down" size="20" color="#999"></u-icon>
          </view>
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">预算范围</text>
          </view>
          <view class="budget-row">
            <input 
              class="budget-input"
              v-model="form.budgetMin"
              placeholder="最低"
              type="number"
              placeholder-class="input-placeholder"
            />
            <text class="budget-separator">-</text>
            <input 
              class="budget-input"
              v-model="form.budgetMax"
              placeholder="最高"
              type="number"
              placeholder-class="input-placeholder"
            />
            <text class="budget-unit">元/时</text>
          </view>
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">授课方式</text>
          </view>
          <view class="teaching-type-grid">
            <view 
              class="type-tag"
              :class="{ active: form.teachingType === 'ONLINE' }"
              @click="selectTeachingType('ONLINE')"
            >
              <u-icon name="rewind-right-fill" :size="28" :color="form.teachingType === 'ONLINE' ? '#fff' : '#5daf34'"></u-icon>
              <text>线上</text>
            </view>
            <view 
              class="type-tag"
              :class="{ active: form.teachingType === 'OFFLINE' }"
              @click="selectTeachingType('OFFLINE')"
            >
              <u-icon name="map-fill" :size="28" :color="form.teachingType === 'OFFLINE' ? '#fff' : '#5daf34'"></u-icon>
              <text>线下</text>
            </view>
            <view 
              class="type-tag"
              :class="{ active: form.teachingType === 'BOTH' }"
              @click="selectTeachingType('BOTH')"
            >
              <u-icon name="checkmark-circle-fill" :size="28" :color="form.teachingType === 'BOTH' ? '#fff' : '#5daf34'"></u-icon>
              <text>都可以</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 详细描述 -->
      <view class="form-section card">
        <view class="section-header">
          <view class="header-icon">
            <u-icon name="edit-pen-fill" size="36" color="#5daf34"></u-icon>
          </view>
          <text class="section-title">详细描述</text>
        </view>

        <view class="form-item textarea-item">
          <view class="item-label">
            <text class="label-text">需求描述</text>
            <text class="required-star">*</text>
          </view>
          <textarea 
            class="item-textarea"
            v-model="form.contentMd"
            placeholder="请详细描述您的需求，包括学习目标、当前水平、期望的教学方式等"
            maxlength="1000"
            placeholder-class="input-placeholder"
          ></textarea>
          <view class="char-count">
            <text>{{ form.contentMd.length }}/1000</text>
          </view>
        </view>

        <view class="form-item textarea-item">
          <view class="item-label">
            <text class="label-text">特殊要求</text>
          </view>
          <textarea 
            class="item-textarea small"
            v-model="form.requirements"
            placeholder="如有其他特殊要求请在此说明（选填）"
            maxlength="500"
            placeholder-class="input-placeholder"
          ></textarea>
          <view class="char-count">
            <text>{{ form.requirements.length }}/500</text>
          </view>
        </view>
      </view>

      <!-- 时间地点 -->
      <view class="form-section card">
        <view class="section-header">
          <view class="header-icon">
            <u-icon name="clock-fill" size="36" color="#5daf34"></u-icon>
          </view>
          <text class="section-title">时间地点</text>
        </view>

        <view class="form-item">
          <view class="item-label">
            <text class="label-text">期望时间</text>
          </view>
          <input 
            class="item-input"
            v-model="preferredTimeInput"
            placeholder="如：周末上午、工作日晚上等"
            maxlength="200"
            placeholder-class="input-placeholder"
            @blur="updatePreferredTime"
          />
        </view>

        <view class="form-item" v-if="form.teachingType !== 'ONLINE'">
          <view class="item-label">
            <text class="label-text">上课地址</text>
          </view>
          <input 
            class="item-input"
            v-model="form.address"
            placeholder="请输入上课地址（线下授课需填写）"
            maxlength="200"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button 
          class="submit-button"
          :class="{ loading: loading }"
          :disabled="loading"
          @click="submitDemand"
        >
          <u-icon v-if="!loading" name="checkmark-circle-fill" size="28" color="#fff"></u-icon>
          <text class="button-text">{{ loading ? '发布中...' : '发布需求' }}</text>
        </button>
      </view>
    </view>

    <!-- 科目选择弹窗 -->
    <u-popup :show="showSubjectPicker" @close="showSubjectPicker = false" mode="bottom" :round="24"
             :safe-area-inset-bottom="true" :closeable="false">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="picker-cancel" @click="showSubjectPicker = false">取消</text>
          <text class="picker-title">选择科目</text>
          <text class="picker-confirm" @click="confirmSubjectSelect">确定</text>
        </view>
        <view class="picker-content">
          <scroll-view scroll-y class="picker-scroll">
            <view
                v-for="(subject, index) in subjectList"
                :key="index"
                class="picker-item"
                :class="{ 'active': selectedSubject === subject }"
                @click="selectedSubject = subject"
            >
              <text class="picker-item-text">{{ subject }}</text>
              <u-icon v-if="selectedSubject === subject" name="checkmark" color="#3cc51f" size="20"></u-icon>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>

    <!-- 年级选择弹窗 -->
    <u-popup :show="showGradePicker" @close="showGradePicker = false" mode="bottom" :round="24"
             :safe-area-inset-bottom="true" :closeable="false">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="picker-cancel" @click="showGradePicker = false">取消</text>
          <text class="picker-title">选择年级</text>
          <text class="picker-confirm" @click="confirmGradeSelect">确定</text>
        </view>
        <view class="picker-content">
          <scroll-view scroll-y class="picker-scroll">
            <view
                v-for="(grade, index) in gradeList"
                :key="index"
                class="picker-item"
                :class="{ 'active': selectedGrade === grade }"
                @click="selectedGrade = grade"
            >
              <text class="picker-item-text">{{ grade }}</text>
              <u-icon v-if="selectedGrade === grade" name="checkmark" color="#3cc51f" size="20"></u-icon>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {publishDemand} from '@/api/demand'
import {getSubjects, getGrades} from '@/api/common'
import {checkLogin} from '@/utils/auth'

export default {
  data() {
    return {
      form: {
        title: '',
        subject: '',
        grade: '',
        budgetMin: '',
        budgetMax: '',
        contentMd: '',
        teachingType: 'BOTH',
        preferredTime: [],
        address: '',
        requirements: '',
        expiresAt: ''
      },
      preferredTimeInput: '',
      expiresAtValue: '',
      subjectList: [],
      gradeList: [],
      subjectLoading: false,
      gradeLoading: false,
      loading: false,
      showSubjectPicker: false,
      showGradePicker: false,
      selectedSubject: '',
      selectedGrade: '',
      submitButtonStyle: {
        background: 'linear-gradient(135deg, #3cc51f 0%, #2ea516 100%)',
        borderRadius: '48rpx',
        height: '96rpx',
        margin: '40rpx 0',
        fontSize: '32rpx',
        fontWeight: '600',
        boxShadow: '0 8rpx 20rpx rgba(60, 197, 31, 0.4)'
      }
    }
  },

  onLoad() {
    // 检查登录状态
    if (!checkLogin()) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/auth/login'
        })
      }, 1500)
      return
    }

    // 加载基础数据
    this.loadSubjects()
    this.loadGrades()
  },

  methods: {
    // 加载科目列表
    async loadSubjects() {
      try {
        this.subjectLoading = true
        const res = await getSubjects()

        if (res.code === 200) {
          console.log('科目数据:', res.data)
          this.subjectList = res.data || []
        } else {
          // 使用默认数据
          this.subjectList = ['数学', '英语', '物理', '化学', '语文', '生物', '历史', '地理', '政治', '计算机', '音乐', '美术', '体育', '其他']
        }
      } catch (error) {
        console.error('加载科目失败:', error)
        // 使用默认数据
        this.subjectList = ['数学', '英语', '物理', '化学', '语文', '生物', '历史', '地理', '政治', '计算机', '音乐', '美术', '体育', '其他']
      } finally {
        this.subjectLoading = false
      }
    },

    // 加载年级列表
    async loadGrades() {
      try {
        this.gradeLoading = true
        const res = await getGrades()

        if (res.code === 200) {
          console.log('年级数据:', res.data)
          this.gradeList = res.data || []
        } else {
          // 使用默认数据
          this.gradeList = ['学前班', '小学一年级', '小学二年级', '小学三年级', '小学四年级', '小学五年级', '小学六年级', '初一', '初二', '初三', '高一', '高二', '高三', '大学', '成人教育', '其他']
        }
      } catch (error) {
        console.error('加载年级失败:', error)
        // 使用默认数据
        this.gradeList = ['学前班', '小学一年级', '小学二年级', '小学三年级', '小学四年级', '小学五年级', '小学六年级', '初一', '初二', '初三', '高一', '高二', '高三', '大学', '成人教育', '其他']
      } finally {
        this.gradeLoading = false
      }
    },

    // 确认科目选择
    confirmSubjectSelect() {
      this.form.subject = this.selectedSubject
      this.showSubjectPicker = false
      console.log('选择的科目:', this.selectedSubject)
    },

    // 确认年级选择
    confirmGradeSelect() {
      this.form.grade = this.selectedGrade
      this.showGradePicker = false
      console.log('选择的年级:', this.selectedGrade)
    },

    // 选择授课方式
    selectTeachingType(type) {
      this.form.teachingType = type
      console.log('授课方式变更:', type)
      // 如果选择线上授课，清空地址
      if (type === 'ONLINE') {
        this.form.address = ''
      }
    },
    
    // 处理授课方式变化
    handleTeachingTypeChange(value) {
      this.selectTeachingType(value)
    },

    // 更新期望时间
    updatePreferredTime() {
      if (this.preferredTimeInput) {
        // 将输入的时间字符串拆分成数组
        this.form.preferredTime = this.preferredTimeInput.split(/[,，、]/).map(t => t.trim()).filter(t => t)
      }
    },

    // 处理过期时间确认
    handleExpiresAtConfirm(e) {
      this.form.expiresAt = e.value
      this.expiresAtValue = e.value
    },

    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return ''
      const date = new Date(datetime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    async submitDemand() {
      if (!this.validateForm()) {
        return
      }

      this.loading = true

      try {
        // 构建请求数据
        const requestData = {
          title: this.form.title,
          subject: this.form.subject,
          grade: this.form.grade || undefined,
          budgetMin: this.form.budgetMin ? parseFloat(this.form.budgetMin) : undefined,
          budgetMax: this.form.budgetMax ? parseFloat(this.form.budgetMax) : undefined,
          contentMd: this.form.contentMd,
          teachingType: this.form.teachingType || 'BOTH',  // 确保传递枚举字符串值
          preferredTime: this.form.preferredTime.length > 0 ? this.form.preferredTime : undefined,
          address: this.form.address || undefined,
          requirements: this.form.requirements || undefined,
          expiresAt: this.form.expiresAt || undefined
        }

        console.log('发布需求数据:', requestData)
        console.log('授课方式值:', this.form.teachingType, '类型:', typeof this.form.teachingType)

        const res = await publishDemand(requestData)
        console.log('发布结果:', res)

        if (res.code === 200) {
          uni.showToast({
            title: res.message || '发布成功',
            icon: 'success'
          })

          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/demand/list'
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '发布失败',
            icon: 'none'
          })
        }

      } catch (error) {
        console.error('发布需求失败:', error)

        // 如果是认证错误，尝试使用测试接口
        if (error.message && error.message.includes('401')) {
          try {
            console.log('尝试使用测试接口...')
            const testRes = await this.testPublishDemand(requestData)

            if (testRes.code === 200) {
              uni.showToast({
                title: '测试发布成功',
                icon: 'success'
              })

              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/demand/list'
                })
              }, 1500)
              return
            }
          } catch (testError) {
            console.error('测试发布也失败:', testError)
          }
        }

        uni.showToast({
          title: error.message || '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 测试发布接口（无需登录）
    async testPublishDemand(data) {
      return uni.request({
        url: 'http://localhost:8866/api/demand/test-publish',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: data
      }).then(res => res.data)
    },

    validateForm() {
      if (!this.form.title || this.form.title.trim() === '') {
        uni.showToast({title: '请输入需求标题', icon: 'none'})
        return false
      }
      if (!this.form.subject) {
        uni.showToast({title: '请选择科目', icon: 'none'})
        return false
      }
      if (!this.form.contentMd || this.form.contentMd.trim() === '') {
        uni.showToast({title: '请输入需求描述', icon: 'none'})
        return false
      }
      if (!this.form.teachingType) {
        uni.showToast({title: '请选择授课方式', icon: 'none'})
        return false
      }
      // 验证授课方式是否为有效枚举值
      const validTeachingTypes = ['ONLINE', 'OFFLINE', 'BOTH']
      if (!validTeachingTypes.includes(this.form.teachingType)) {
        console.error('无效的授课方式:', this.form.teachingType)
        uni.showToast({title: '授课方式选择有误，请重新选择', icon: 'none'})
        return false
      }
      // 如果是线下或都可以，且没有填写地址，给出提示
      if ((this.form.teachingType === 'OFFLINE' || this.form.teachingType === 'BOTH') && !this.form.address) {
        uni.showModal({
          title: '提示',
          content: '您选择了线下授课，建议填写上课地址以便教员联系',
          showCancel: false
        })
      }
      if (this.form.budgetMin && this.form.budgetMax) {
        if (parseFloat(this.form.budgetMin) > parseFloat(this.form.budgetMax)) {
          uni.showToast({title: '最低预算不能大于最高预算', icon: 'none'})
          return false
        }
      }
      return true
    },

    // 返回
    goBack() {
      uni.showModal({
        title: '提示',
        content: '确定要放弃发布需求吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },

    // 显示帮助
    showHelp() {
      uni.showModal({
        title: '发布帮助',
        content: '1. 请详细填写需求信息\n2. 预算范围有助于匹配合适的教员\n3. 详细描述能提高匹配成功率',
        showCancel: false,
        confirmText: '知道了'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-demand-container {
  background: #f8f9fa;
  min-height: 100vh;
  position: relative;
  padding-bottom: 180rpx;
}

.tips-banner {
  display: flex;
  align-items: center;
  gap: 16rpx;
  background: linear-gradient(135deg, #e8f5e9, #f1f8f4);
  padding: 24rpx 30rpx;
  margin: 30rpx;
  border-radius: 16rpx;
  border-left: 6rpx solid #5daf34;

  .tips-text {
    font-size: 28rpx;
    color: #5daf34;
    font-weight: 500;
  }
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  padding-top: var(--status-bar-height, 44px);
  height: calc(88rpx + var(--status-bar-height, 44px));
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 30rpx;
  padding-right: 30rpx;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;

  .navbar-left, .navbar-right {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;

    &:active {
      background-color: #f5f5f5;
      transform: scale(0.95);
    }
  }

  .navbar-title {
    flex: 1;
    text-align: center;
    color: #333;
    font-size: 36rpx;
    font-weight: 600;
  }
}

.form-section {
  background: white;
  margin: 0 30rpx 30rpx;
  padding: 40rpx 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);

  .section-header {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    padding-bottom: 24rpx;
    border-bottom: 2rpx solid #f0f0f0;

    .header-icon {
      width: 70rpx;
      height: 70rpx;
      background: linear-gradient(135deg, rgba(93, 175, 52, 0.1), rgba(124, 179, 66, 0.1));
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }

    .section-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.form-item {
  margin-bottom: 36rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .item-label {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .label-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }

    .required-star {
      color: #ff6b6b;
      margin-left: 8rpx;
      font-size: 32rpx;
      line-height: 1;
    }
  }

  .item-input {
    width: 100%;
    height: 88rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &:focus {
      background: white;
      border-color: #5daf34;
    }
  }

  .picker-wrapper {
    height: 88rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &:active {
      border-color: #5daf34;
    }

    .placeholder {
      color: #bbb;
    }

    text {
      color: #333;
    }
  }
}

.budget-row {
  display: flex;
  align-items: center;
  gap: 16rpx;

  .budget-input {
    flex: 1;
    height: 88rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &:focus {
      background: white;
      border-color: #5daf34;
    }
  }

  .budget-separator {
    font-size: 28rpx;
    color: #999;
  }

  .budget-unit {
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
    min-width: 100rpx;
    text-align: right;
  }
}

.teaching-type-grid {
  display: flex;
  gap: 16rpx;

  .type-tag {
    flex: 1;
    padding: 24rpx 16rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
    border: 2rpx solid #e8e8e8;
    transition: all 0.3s;

    text {
      font-size: 26rpx;
      color: #666;
    }

    &.active {
      background: linear-gradient(135deg, #5daf34, #7cb342);
      border-color: #5daf34;
      box-shadow: 0 4rpx 16rpx rgba(93, 175, 52, 0.3);

      text {
        color: white;
      }
    }

    &:active {
      transform: scale(0.95);
    }
  }
}

.textarea-item {
  .item-textarea {
    width: 100%;
    min-height: 300rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    padding: 24rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    border: 2rpx solid transparent;
    transition: all 0.3s;

    &:focus {
      background: white;
      border-color: #5daf34;
    }
    
    &.small {
      min-height: 200rpx;
    }
  }

  .char-count {
    text-align: right;
    margin-top: 12rpx;

    text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.input-placeholder {
  color: #bbb;
}

// 弹窗选择器样式
.picker-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.picker-cancel {
  color: #666;
  font-size: 32rpx;
}

.picker-title {
  color: #333;
  font-size: 36rpx;
  font-weight: 600;
}

.picker-confirm {
  color: #3cc51f;
  font-size: 32rpx;
  font-weight: 600;
}

.picker-content {
  height: 600rpx;
  overflow: hidden;
}

.picker-scroll {
  height: 600rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  border-bottom: 1px solid #f5f5f5;
  transition: all 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &.active {
    background: #f0f9ff;

    .picker-item-text {
      color: #3cc51f;
      font-weight: 600;
    }
  }

  &:active {
    background: #f8f8f8;
  }
}

.picker-item-text {
  color: #333;
  font-size: 32rpx;
  transition: all 0.3s ease;
}

.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  color: #333;
  min-height: 60rpx;
}

.submit-section {
  padding: 0 30rpx;
  margin-top: 40rpx;

  .submit-button {
    width: 100%;
    height: 100rpx;
    background: linear-gradient(135deg, #5daf34, #7cb342);
    border: none;
    border-radius: 50rpx;
    font-size: 34rpx;
    font-weight: bold;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    box-shadow: 0 8rpx 32rpx rgba(93, 175, 52, 0.35);
    transition: all 0.3s;

    &:active:not(.loading) {
      transform: scale(0.98);
      box-shadow: 0 4rpx 20rpx rgba(93, 175, 52, 0.25);
    }

    &.loading {
      opacity: 0.7;
    }
    
    .button-text {
      color: white;
    }
  }
}
</style>
